# *-*coding:utf8*-*#
__author__ = 'guo'
from django.shortcuts import render, redirect, render_to_response, HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth import decorators
from libs.Base import *
from libs.auth import *
from django.contrib import auth
import hashlib
from django.views.decorators.csrf import csrf_exempt
# Create your views here.


# 后台管理页面 主页
@decorators.login_required(login_url="/crm/login/")
def index(request):
    return render(request, 'index/index.html', locals())


@decorators.login_required(login_url="/crm/login/")
def changepwd(request):
    if request.method == "POST":
        oldPassword = request.POST.get("oldPassword").strip()
        if auth.authenticate(username=request.user.username, password=oldPassword) is None:
            return OutJson(300, "旧密码不正确")
        newPassword = request.POST.get("newPassword").strip()
        rnewPassword = request.POST.get("rnewPassword").strip()
        if newPassword != rnewPassword:
            return OutJson(300, "两次新密码不一致")
        userinfo = User.objects.filter(id=request.user.id).update(
                password = request.user.hashed_password(newPassword)
        )
        if userinfo > 0:
            return OutJson(200,"修改密码成功", "/crm/logout/")
        else:
            return OutJson(300,"修改密码失败")
    else:
        return render(request, "index/changepwd.html", locals())



@decorators.login_required(login_url="/crm/login/")
def edit(request):
    if request.method == "POST":
            userinfo = User.objects.filter(id=request.user.id).update(
                    username = request.POST.get("username"),
                    mobile = request.POST.get("mobile"),
                    email = request.POST.get("email"),
            )
            if userinfo > 0:
                return OutJson(200,"更新资料成功")
            else:
                return OutJson(200,"更新资料失败")
    else:
        return render(request, "index/edit.html", locals())




# 登录页面
# @csrf_exempt
def login(request):
    error = ""
    if request.method == "POST":
        username = request.POST.get("username").strip()
        password = request.POST.get("password").strip()
        if username == "" or username.isspace() or password == "" or password.isspace():
            error = "用户名和密码不能为空"
            return render(request, 'index/login.html', locals())
        user = auth.authenticate(username=username, password=password)
        print(user)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                if request.user.is_authenticated() == False:
                    error = "登录失败"
            else:
                error = user.username+"已被暂时禁用"
        else:
            error = "用户名或密码不正确，请重试"

        if error != "":
            return render(request, 'index/login.html', locals())
        else:
            return HttpResponseRedirect("/crm/index/")
    else:
        return render(request, 'index/login.html', locals())


#注册页面
def reg(request):
    if request.method == "POST":
        username = request.POST.get("username").strip()
        password = request.POST.get("password").strip()
        dpassword = request.POST.get("dpassword").strip()
        if password != dpassword:
            error = "两次密码不一致"
            return render(request, "index/register.html", locals())
        useType = checkUser(username)
        if useType == "EMAIL":
            emailIsHave = User.objects.filter(email=username)
            if len(emailIsHave) > 0:
                error = "此邮箱地址已注册过"
                return render(request, "index/register.html", locals())
            user = User.objects.create(
                email=username,
                password=hashlib.md5(password.encode("utf8")).hexdigest(),
            )
        elif useType == "MOBILE":
            mobileIsHave = User.objects.filter(mobile=username)
            if len(mobileIsHave) > 0:
                error = "此手机号码已注册过"
                return render(request, "index/register.html", locals())
            user = User.objects.create(
                mobile=username,
                password=hashlib.md5(password.encode("utf8")).hexdigest(),
            )
        else:
            usernameIsHave = User.objects.filter(username=username)
            if len(usernameIsHave) > 0:
                error = "此用户名已注册过"
                return render(request, "index/register.html", locals())
            user = User.objects.create(
                username=username,
                password=hashlib.md5(password.encode("utf8")).hexdigest(),
            )
        if user:
            return HttpResponseRedirect("/crm/index")
    else:
        return render(request, 'index/register.html', locals())

#登出页面
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/crm/login/")

@csrf_exempt
def uedit(request):
    if request.GET.get("action") == "config":
        ueconfig = {}
        ueconfig["imageActionName"] = "uploadimage"
        ueconfig["imageFieldName"] = "upfile"
        ueconfig["imageMaxSize"] = 2048000
        ueconfig["imageAllowFiles"] = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
        ueconfig["imageCompressEnable"] = "true"
        ueconfig["imageCompressBorder"] = 1600
        ueconfig["imageInsertAlign"] = "none"
        ueconfig["imageUrlPrefix"] = ""
        ueconfig["imagePathFormat"] = "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
        returnJson = json.dumps(ueconfig)
    elif request.GET.get("action") == "uploadimage":
        # from PIL import Image
        # try:
        #         reqfile = request.FILES['picfile']#picfile要和html里面一致
        #         img = Image.open(reqfile)
        #         img.thumbnail((500,500),Image.ANTIALIAS)#对图片进行等比缩放
        #         img.save("/Users/bcc/Desktop/python/bbs/Image/a.png","png")#保存图片
        # except Exception as e:
        #        return HttpResponse("Error %s"%e)#异常，查看报错信息

        test = {}
        returnJson = test["meta"] = request.META
    return HttpResponse(returnJson, content_type='application/json')

